
package gui.mpm;

import java.sql.Timestamp;
import java.util.ArrayList;

import javax.swing.table.DefaultTableModel;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.DefaultComboBoxModel;
import javax.swing.border.BevelBorder;
import javax.swing.border.MatteBorder;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.ListSelectionModel;

import utilities.Services;
import entities.ProductionOrder;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.RowSpec;

import net.miginfocom.swing.MigLayout;

import javax.swing.ImageIcon;

import java.awt.SystemColor;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;

/**
 * @author Idan
 * GUI class for creation of orders in the System
 */
public class MPMPanel extends javax.swing.JPanel
{

    /**
     * Creates new form MPMPanel
     */
	private JFrame myframe;
    public MPMPanel(JFrame frame)
    {
    	setBackground(new Color(173, 216, 230));
    	this.myframe=frame;
        initComponents();
        
        
    }


    private void initComponents() 
    {

      
       
                setLayout(new MigLayout("", "[::60px,grow][grow][::60px,grow]", "[::60px,grow][][][][][::60px,grow]"));
                                quantityTextField = new javax.swing.JTextField();
                                quantityTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
                                quantityTextField.setColumns(3);
                                
                                        quantityTextField.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
                                        add(quantityTextField, "flowx,cell 1 1,alignx center,aligny top");
                
                clearButton = new javax.swing.JButton();
                clearButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
                clearButton.setIcon(new ImageIcon(MPMPanel.class.getResource("/graphics/clear.png")));
                clearButton.addMouseListener(new MouseAdapter() {
                	
                	@Override
                	public void mouseClicked(MouseEvent arg0)
                	{
                		// Clear all text fields
                		clearAllTextFields();    
                		
                	}
                });
                
                        clearButton.setText("נקה");
                        add(clearButton, "flowx,cell 1 2,alignx center,aligny bottom");
                jPanel1 = new javax.swing.JPanel(){@Override
        			public void paintComponent(Graphics g) {
        	        Graphics2D g2d = (Graphics2D) g;
        	        Color color1 = getBackground();
        	        Color color2 = color1.darker();
        	        int w = getWidth();
        	        int h = getHeight(); 
        	        GradientPaint gp = new GradientPaint(
        	                0, 0, color1,
        	                0, h, color2);

        	        g2d.setPaint(gp);
        	        g2d.fillRect(0, 0, w, h);
        	        }};
                jPanel1.setBackground(new Color(173, 216, 230));
                jScrollPane2 = new javax.swing.JScrollPane();
                jTable1 = new javax.swing.JTable();
                jTable1.setFont(new Font("Tahoma", Font.PLAIN, 15));
                jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                jTable1.setBorder(new TitledBorder(null, "", TitledBorder.RIGHT, TitledBorder.TOP, null, new Color(59, 59, 59)));
                deleteOrderButton = new javax.swing.JButton();
                deleteOrderButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
                deleteOrderButton.setIcon(new ImageIcon(MPMPanel.class.getResource("/graphics/delete.png")));
                deleteOrderButton.addMouseListener(new MouseAdapter() {
                	@Override
                	public void mouseClicked(MouseEvent arg0)
                	{
                		
                		Object[] options = {"כן","לא"};
                		int n = JOptionPane.showOptionDialog(myframe, "האם ברצונך למחוק את הפק''ע?","אישור מחיקה", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,"");
                		
                		if (n==0)
                		{
                    		int rowNumber = jTable1.getSelectedRow();
                    		if (rowNumber==-1)
                    		{
                    			JOptionPane.showMessageDialog(myframe,
                    				    "יש לבחור ראשית פק''ע למחיקה מהרשימה.","שגיאה",JOptionPane.ERROR_MESSAGE);
                    		}
                    		else
                    		{
	            		disableAll();
	            		String value = jTable1.getValueAt(rowNumber, 4).toString();
	            	//	System.out.println(value + " at row " + rowNumber);
	            		deleteOrder(value, rowNumber);
                    		}
                    		
                		}
                	

			
                }});
                
                        jPanel1.setBorder(new TitledBorder(null, "\u05E8\u05E9\u05D9\u05DE\u05EA \u05E4\u05E7''\u05E2\u05D5\u05EA \u05E4\u05EA\u05D5\u05D7\u05D5\u05EA", TitledBorder.RIGHT, TitledBorder.TOP, null, new Color(59, 59, 59)));
                        
                                jTable1.setModel(new DefaultTableModel(
                                	new Object[][] {
                                	},
                                	new String[] {
                                		"\u05DB\u05DE\u05D5\u05EA", "\u05D3\u05D9\u05D5\u05E4\u05D8\u05E8", "\u05DE\u05D5\u05E6\u05E8", "\u05EA\u05D0\u05E8\u05D9\u05DA", "\u05E4\u05E7\"\u05E2"
                                	}
                                ) {
                                	boolean[] columnEditables = new boolean[] {
                                		false, false, false, false, false
                                	};
                                	public boolean isCellEditable(int row, int column) {
                                		return columnEditables[column];
                                	}
                                });
                                jTable1.getColumnModel().getColumn(0).setPreferredWidth(50);
                                jTable1.getColumnModel().getColumn(0).setMinWidth(50);
                                jTable1.getColumnModel().getColumn(1).setPreferredWidth(50);
                                jTable1.getColumnModel().getColumn(1).setMinWidth(50);
                                jTable1.getColumnModel().getColumn(2).setPreferredWidth(100);
                                jTable1.getColumnModel().getColumn(2).setMinWidth(100);
                                jTable1.getColumnModel().getColumn(3).setPreferredWidth(100);
                                jTable1.getColumnModel().getColumn(3).setMinWidth(100);
                                jTable1.getColumnModel().getColumn(4).setPreferredWidth(110);
                                jTable1.getColumnModel().getColumn(4).setMinWidth(110);
                                jTable1.getTableHeader().setReorderingAllowed(false);
                                jScrollPane2.setViewportView(jTable1);
                                
                                        deleteOrderButton.setText("מחק פק\"ע");
                                        deleteOrderButton.addActionListener(new java.awt.event.ActionListener()
                                        {
                                            public void actionPerformed(java.awt.event.ActionEvent evt)
                                            {
                                                jButton3ActionPerformed(evt);
                                            }
                                        });
                                        add(jPanel1, "cell 1 3,alignx center,aligny center");
                                        jPanel1.setLayout(new FormLayout(new ColumnSpec[] {
                                        		ColumnSpec.decode("1px"),
                                        		ColumnSpec.decode("456px:grow"),},
                                        	new RowSpec[] {
                                        		FormFactory.PARAGRAPH_GAP_ROWSPEC,
                                        		RowSpec.decode("304px"),
                                        		FormFactory.RELATED_GAP_ROWSPEC,
                                        		RowSpec.decode("default:grow"),}));
                                        jPanel1.add(jScrollPane2, "2, 2, center, fill");
                                        jPanel1.add(deleteOrderButton, "2, 4, left, top");
                quantityLabel = new javax.swing.JLabel();
                quantityLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
                
                        quantityLabel.setText("כמות:");
                        add(quantityLabel, "cell 1 1,alignx center,aligny center");
                        
                        diopterTextField = new JTextField();
                        diopterTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
                        diopterTextField.addActionListener(new ActionListener() {
                        	public void actionPerformed(ActionEvent e)
                        	{
                        		quantityTextField.requestFocus();
                        	}
                        });
                        diopterTextField.setColumns(3);
                        add(diopterTextField, "cell 1 1,alignx center,aligny top");
                        diopterLabel = new javax.swing.JLabel();
                        diopterLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
                        
                                diopterLabel.setText("דיופטר:");
                                add(diopterLabel, "cell 1 1,alignx center");
                                exitButton = new javax.swing.JButton();
                                exitButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
                                exitButton.setIcon(new ImageIcon(MPMPanel.class.getResource("/graphics/exit.png")));
                                exitButton.setText("יציאה מהמערכת");
                                exitButton.addMouseListener(new MouseAdapter()
                                {
                                	@Override
                                	public void mouseClicked(MouseEvent arg0) 
                                	{
                                		
                                		Object[] options = {"כן","לא"};
                                		int n = JOptionPane.showOptionDialog(myframe, "האם ברצונך לצאת מהמערכת?","אישור יציאה", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,"");
                                		
                                		if (n==0)
                                		{
                                    		
                                			if (MPMFrame.mpmClient!= null)
                                            {
                                              try
                                              {
                                            	  MPMFrame.mpmClient.close();
                                              }
                                              catch (Exception ignore)
                                              {}
                                             }
                                    		
                                    		System.exit(0);
                                    	}
                                    		
                                    		
                                		//Close connections to the server
                                		
                                	}
                                });
                                add(exitButton, "cell 1 4,alignx center,aligny top");
                                
                                        itemTypeComboBox = new javax.swing.JComboBox();
                                        itemTypeComboBox.setFont(new Font("Tahoma", Font.PLAIN, 13));
                                        itemTypeComboBox.addActionListener(new java.awt.event.ActionListener() {
                                            public void actionPerformed(java.awt.event.ActionEvent evt) {
                                                itemTypeComboBoxActionPerformed(evt);
                                            }
                                        });
                                        add(itemTypeComboBox, "cell 1 1,alignx center");
                                        itemTypeLabel = new javax.swing.JLabel();
                                        itemTypeLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
                                        
                                                itemTypeLabel.setText("מוצר:");
                                                add(itemTypeLabel, "cell 1 1,alignx center");
                                                orderIDTextField = new javax.swing.JTextField();
                                                orderIDTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
                                                orderIDTextField.addActionListener(new ActionListener() {
                                                	public void actionPerformed(ActionEvent e) 
                                                	{
                                                		String order = orderIDTextField.getText();
                                                		if (order.length() > 7)
                                        				{
                                        					order = order.substring(3); // remove the first 3 characters
                                        					orderIDTextField.setText(order);
                                        				}
                                                		itemTypeComboBox.requestFocus();
                                                	}
                                                });
                                                orderIDTextField.setColumns(8);
                                                add(orderIDTextField, "cell 1 1,alignx center");
                                                orderIDLabel = new javax.swing.JLabel();
                                                orderIDLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
                                                
                                                        orderIDLabel.setText("פק\"ע:");
                                                        add(orderIDLabel, "cell 1 1,alignx center");
                                                        createOrderButton = new javax.swing.JButton();
                                                        createOrderButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
                                                        createOrderButton.setIcon(new ImageIcon(MPMPanel.class.getResource("/graphics/createOrder.png")));
                                                        createOrderButton.addMouseListener(new MouseAdapter() {
                                                        	
                                                        	
                                                        	@Override
                                                        	public void mouseClicked(MouseEvent arg0)
                                                        	{
                                                        		if (quantityTextField.getText().equals(""))
                                                        		{
                                                        			JOptionPane.showMessageDialog(myframe,
                                                        				    "יש למלא את שדה הכמות.","שגיאה",JOptionPane.ERROR_MESSAGE);
                                                        		}
                                                        		else
                                                        		if (diopterTextField.getText().equals(""))
                                                        		{
                                                        			JOptionPane.showMessageDialog(myframe,
                                                        				    "יש למלא את שדה הדיופטר.","שגיאה",JOptionPane.ERROR_MESSAGE);
                                                        		}
                                                        		else
                                                        		if (orderIDTextField.getText().equals(""))
                                                        		{
                                                        			JOptionPane.showMessageDialog(myframe,
                                                        				    "יש למלא את שדה הפק''ע.","שגיאה",JOptionPane.ERROR_MESSAGE);
                                                        		}
                                                        		else
                                                        		if (!utilities.Services.isNumeric(quantityTextField.getText()))
                                                        		{
                                                        			JOptionPane.showMessageDialog(myframe,
                                                        				    "הערך בשדה הכמות חייב להיות מספר.","שגיאה",JOptionPane.ERROR_MESSAGE);
                                                        		}
                                                        		else
                                                        		if (!utilities.Services.isNumeric(orderIDTextField.getText()))
                                                            	{
                                                            		JOptionPane.showMessageDialog(myframe,
                                                            			    "הערך בשדה פק''ע חייב להיות מספר.","שגיאה",JOptionPane.ERROR_MESSAGE);
                                                            	}
                                                            	else
                                                        		if (!utilities.Services.isNumeric(diopterTextField.getText()))
                                                        		{
                                                        			JOptionPane.showMessageDialog(myframe,
                                                        				    "הערך בשדה הדיופטר חייב להיות מספר.","שגיאה",JOptionPane.ERROR_MESSAGE);
                                                        		}
                                                        		else
                                                        		if (!utilities.Services.isNumeric(diopterTextField.getText()))
                                                        		{
                                                        			JOptionPane.showMessageDialog(myframe,
                                                        				    "הערך בשדה הפק''ע חייב להיות מספר.","שגיאה",JOptionPane.ERROR_MESSAGE);
                                                        		}
                                                        		else
                                                        		{
                                                        			// Everything is o.k
                                                        
                                                        			createNewOrder();
                                                        			
                                                        		}
	  
                                                        	}	
                                                        }        );
                                                        
                                                                createOrderButton.setText("צור פק\"ע");
                                                                add(createOrderButton, "cell 1 2,alignx center,aligny top");
    }

    private void itemTypeComboBoxActionPerformed(java.awt.event.ActionEvent evt) 
    {
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    }

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
    }
    private javax.swing.JLabel diopterLabel;
    private javax.swing.JComboBox itemTypeComboBox;
    private javax.swing.JLabel itemTypeLabel;
    private javax.swing.JButton createOrderButton;
    private javax.swing.JButton clearButton;
    private javax.swing.JButton deleteOrderButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel orderIDLabel;
    private javax.swing.JTextField orderIDTextField;
    private javax.swing.JLabel quantityLabel;
    private javax.swing.JTextField quantityTextField;
    private JTextField diopterTextField;


    void setVariables(ArrayList<Object> response)
    {	
    	ArrayList<Object> listOfOrders = (ArrayList<Object>) response.get(1);
   		ArrayList<Object> listOfProducts = (ArrayList<Object>) response.get(2);
    	
    
    	
        int j=2;
        for (int i=1; i<=((int)listOfOrders.get(1));i++)
        {
            DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
            model.addRow(new Object[]{listOfOrders.get(j+4).toString(),listOfOrders.get(j+3).toString(),listOfOrders.get(j+2).toString(),listOfOrders.get(j+1).toString(),listOfOrders.get(j+0).toString()});
            j=j+5;
        }
        
    	
    	
        for (int k=1; k<=((int)listOfProducts.get(1));k++)
        {
        	this.itemTypeComboBox.addItem(Services.createObject(listOfProducts.get(k+1).toString() ) );        	
        }
        
      
      
    }


    /**
     * Clear GUI text fields
     */
    private void clearAllTextFields()
	{
		diopterTextField.setText("");
		quantityTextField.setText("");
		orderIDTextField.setText("");  
	}
    
    /**
     * Creates a new order in the System
     */
    private void createNewOrder()
	{
		ArrayList<Object> message = new ArrayList<Object>();
		ArrayList<Object> response = null;
		message.add("createNewOrder");
		ProductionOrder newOrder = new ProductionOrder();
		newOrder.setOrderID(Integer.parseInt(orderIDTextField.getText()));
		newOrder.setDiopter(Float.parseFloat(diopterTextField.getText()));
		newOrder.setQuantity(Integer.parseInt(quantityTextField.getText()));
		newOrder.setStatusID(1);
		newOrder.setType(itemTypeComboBox.getSelectedItem().toString());
		newOrder.setOrderDate(new Timestamp(System.currentTimeMillis()));
		message.add(newOrder);
		disableAll();
		try
		{
			response = MPMFrame.mpmClient.call(message);
			enableAll();
			
			if (response.get(0).toString().equalsIgnoreCase("Failed"))
			{
				JOptionPane.showMessageDialog(myframe,
    				    "ארעה שגיאה בביצוע הפעולה.","שגיאה",JOptionPane.ERROR_MESSAGE);
			}
			else
			if (response.get(0).toString().equalsIgnoreCase("SQL Failed"))
			{
				JOptionPane.showMessageDialog(myframe,
    				    "ארעה שגיאה בשרת בסיס הנתונים.","שגיאה",JOptionPane.ERROR_MESSAGE);
						
			}					
			else
			if (response.get(0).toString().equalsIgnoreCase("failedToConvert"))
			{
				JOptionPane.showMessageDialog(myframe,
    				    "ארעה שגיאה בהעברת הבקשה לשרת.","שגיאה",JOptionPane.ERROR_MESSAGE);
			}
			else
			if(response.get(0).toString().equalsIgnoreCase("Failed in createNewOrder"))
			{
				JOptionPane.showMessageDialog(myframe,
    				    "פק''ע זו כבר קיימת במערכת.","שגיאה",JOptionPane.ERROR_MESSAGE); 
			}
			else
			{	
				// Valid, order was created in the DB
				 DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		         model.addRow(new Object[]{String.valueOf(newOrder.getQuantity()), String.valueOf(newOrder.getDiopter()), newOrder.getType(), newOrder.getDateAsString(), String.valueOf(newOrder.getOrderID())});
		         clearAllTextFields();  
			}
			
		} 
		catch (Exception e)
		{
			
			//e.printStackTrace();
		}
		
	
		
	}
	
	/**
	 * Enable GUI elements
	 */
	private void enableAll() 
	{
		createOrderButton.setEnabled(true);
		clearButton.setEnabled(true);
		deleteOrderButton.setEnabled(true);
		exitButton.setEnabled(true);
	}

	/**
	 * Disable GUI elements
	 */
	private void disableAll()
	{
		createOrderButton.setEnabled(false);
		clearButton.setEnabled(false);
		deleteOrderButton.setEnabled(false);
		exitButton.setEnabled(false);				
	}
	
	/**
	 * Delete an order from the system
	 */
	private void deleteOrder(String value, int rowNumber) 
	{
		ArrayList<Object> message = new ArrayList<Object>();
		ArrayList<Object> response = new ArrayList<Object>();
		ProductionOrder deleteOrder = new ProductionOrder();
		deleteOrder.setOrderID(Integer.parseInt(value));
		message.add("deleteOrder");
		message.add(deleteOrder);
		try {
			response = MPMFrame.mpmClient.call(message);
			
			if (response.get(0).toString().equalsIgnoreCase("failedToDeleteOrder"))
    		{
				JOptionPane.showMessageDialog(myframe,
    				    "ארעה שגיאה בביצוע הפעולה.","שגיאה",JOptionPane.ERROR_MESSAGE);

    		}
    		else
    		{
    			
    			 DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		        model.removeRow(rowNumber);
		        JOptionPane.showMessageDialog(myframe,"הפק''ע נמחקה.","אישור",JOptionPane.INFORMATION_MESSAGE);
    			
    		}

		} catch (Exception e)
		{
			
			//e.printStackTrace();
		}
		
		enableAll();
		
	}
	
	@Override
	public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color color1 = getBackground();
    Color color2 = color1.darker();
    int w = getWidth();
    int h = getHeight(); 
    GradientPaint gp = new GradientPaint(
            0, 0, color1,
            0, h, color2);

    g2d.setPaint(gp);
    g2d.fillRect(0, 0, w, h);
    }
	
}
